package com.sh.dc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sh.dc.common.pojo.bo.EnvBO;
import com.sh.dc.common.pojo.bo.SolverCmdParam;
import com.sh.dc.common.pojo.bo.SolverFileParam;
import com.sh.dc.common.pojo.dto.SolverDto;
import com.sh.dc.common.pojo.query.SolverPageQuery;
import io.micrometer.common.util.StringUtils;
import com.sh.dc.entity.Solver;
import com.sh.dc.mapper.SolverMapper;
import com.sh.dc.service.ISolverService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 求解器表 服务实现类
 * </p>
 *
 * @author zhenlan
 * @since 2024-07-15
 */
@Service
public class SolverServiceImpl extends ServiceImpl<SolverMapper, Solver> implements ISolverService {

    @Autowired
    private SolverMapper solverMapper;

    @Override
    public IPage<SolverDto> getSolverPage(SolverPageQuery query) {
        IPage<Solver> page = new Page<>(query.getPageNum(), query.getPageSize());
        QueryWrapper<Solver> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(query.getName())) {
            queryWrapper.like("name", query.getName());
        }
        if (StringUtils.isNotBlank(query.getNameEn())) {
            queryWrapper.like("name_en", query.getNameEn());
        }
        if (StringUtils.isNotBlank(query.getProduct())) {
            queryWrapper.like("product", query.getProduct());
        }
        if (StringUtils.isNotBlank(query.getCreateBy())) {
            queryWrapper.like("create_by", query.getCreateBy());
        }
        IPage<Solver> result = solverMapper.selectPage(page, queryWrapper);
        return result.convert(this::transferToDto);
    }

    @Override
    public SolverDto transferToDto(Solver solver) {
        if (solver == null) {
            return null;
        }
        SolverDto solverDto = new SolverDto();
        BeanUtil.copyProperties(solver, solverDto);
        if (StringUtils.isNotBlank(solver.getEnvs())) {
            solverDto.setEnvList(JSON.parseArray(solver.getEnvs(), EnvBO.class));
        }
        if (StringUtils.isNotBlank(solver.getFileParams())) {
            solverDto.setFileParamList(JSON.parseArray(solver.getFileParams(), SolverFileParam.class));
        }
        if (StringUtils.isNotBlank(solver.getCmdParams())) {
            solverDto.setCmdParamList(JSON.parseArray(solver.getCmdParams(), SolverCmdParam.class));
        }
        return solverDto;
    }

}
